package com.wan37.logic.dao.impl;


import com.wan37.logic.dao.UserDao;
import com.wan37.logic.domain.entity.UserDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-06-01 16:50
 **/
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = Exception.class)
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Override
    public boolean add(UserDO userDO) {
        try {
            hibernateTemplate.save(userDO);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean delete(String userId) {
        try {
            hibernateTemplate.delete(userId);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(UserDO userDO) {
        try {
            Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
            Query query = session.createQuery("update UserDO set gold=?,ingot=?,backpackNumber=?,nickname=? where userId = ?");
            query.setParameter(0, userDO.getGold());
            query.setParameter(1, userDO.getIngot());
            query.setParameter(2, userDO.getBackpackNumber());
            query.setParameter(3, userDO.getNickname());
            query.setParameter(4, userDO.getUserId());
            query.executeUpdate();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public UserDO getUserByUserId(String userId) {
        //TODO 尽量不要用被抛弃的方法
        List<UserDO> list = (List<UserDO>) hibernateTemplate.find("from UserDO where userId = ?", userId);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<UserDO> getAllUsers() {
        return (List<UserDO>) hibernateTemplate.find("from User");
    }
}
